package top.jle.spring.basic.fis.codec;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

public class RedissonFastJSON2Codec extends BaseCodec {

    public static final RedissonFastJSON2Codec INSTANCE = new RedissonFastJSON2Codec();

    /**
     * 编码器
     */
    private final Encoder encoder = in -> {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        try(ByteBufOutputStream out = new ByteBufOutputStream(byteBuf)){
            JSON.writeTo(out,in, JSONWriter.Feature.WriteClassName);
            return out.buffer();
        }finally {
            byteBuf.release();
        }
    };
    /*
     * 解码器
     */
    private final Decoder<Object> decoder = (buf, state) -> JSON.parseObject(new ByteBufInputStream(buf),Object.class, JSONReader.Feature.SupportAutoType);

    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }
}
